﻿package com.vigmonk.utils
{
	import flash.display.MovieClip;
	import flash.events.Event;	
	import flash.utils.Dictionary;

	public class FrameCtrl
	{
		private var mcDic:Dictionary;
		private static var instance:FrameCtrl;
		
		public function FrameCtrl()
		{
			mcDic = new Dictionary();
		}
		
		//
		public static function getInstance():FrameCtrl 
		{
			if(instance==null) instance = new FrameCtrl();
			return instance;
		}
		
		//________________________________________________ 프레임 유틸
		
		// 
		public function nextPlay(_mc:MovieClip,_num:Number=NaN):void
		{
			mcDic[_mc] = {stat:'next',tarNum:_num};
			
			removeEnterFrame(_mc);
			_mc.addEventListener(Event.ENTER_FRAME,onEnter);
		}
		
		//
		public function prevPlay(_mc:MovieClip,_num:Number=NaN):void
		{
			mcDic[_mc] = {stat:'prev',tarNum:_num};
			
			removeEnterFrame(_mc);
			_mc.addEventListener(Event.ENTER_FRAME,onEnter);
		}
		
		//
		private function onEnter(_e:Event):void
		{
			
			var mc:MovieClip = _e.target as MovieClip;
			var tarNum = mcDic[mc].tarNum;
			if(mcDic[mc].stat == 'next'){
				mc.nextFrame();
				if(isNaN(tarNum)){
					if(mc.currentFrame==mc.totalFrames) removeDic(mc);
				}else{
					if(mc.currentFrame==tarNum) {
						removeDic(mc);	
					}
				}
			}else{
				mc.prevFrame();
				if(isNaN(tarNum)){
					if(mc.currentFrame==1) removeDic(mc);
				}else{
					if(mc.currentFrame==tarNum) {
						removeDic(mc);	
					}
				}
			}
		}
		
		
		//
		private function removeDic(_mc:MovieClip):void
		{
			delete mcDic[_mc];
			removeEnterFrame(_mc);
		}
		//
		private function removeEnterFrame(_mc:MovieClip):void
		{
			_mc.removeEventListener(Event.ENTER_FRAME,onEnter);
		}
		
	}
}